// 定义（或者获取）商品数据
const productData = [
  {
    id: 1001,
    imgUrl: "./imgs/apple.png",
    title: "苹果",
    titleEn: "Apple",
    price: 2.99,
  },
  {
    id: 1002,
    imgUrl: "./imgs/beer.png",
    title: "啤酒",
    titleEn: "Beer",
    price: 14.99,
  },
  {
    id: 1003,
    imgUrl: "./imgs/milk.png",
    title: "牛奶",
    titleEn: "Milk",
    price: 4.99,
  },
  {
    id: 1004,
    imgUrl: "./imgs/doughnut.png",
    title: "甜甜圈",
    titleEn: "Doughnut",
    price: 19.99,
  },
  {
    id: 1005,
    imgUrl: "./imgs/bread.png",
    title: "面包",
    titleEn: "Bread",
    price: 3.99,
  },
  {
    id: 1006,
    imgUrl: "./imgs/aubergine.png",
    title: "茄子",
    titleEn: "Aubergine",
    price: 3.49,
  },
  {
    id: 1007,
    imgUrl: "./imgs/lettuce.png",
    title: "生菜",
    titleEn: "Lettuce",
    price: 2.99,
  },
  {
    id: 1008,
    imgUrl: "./imgs/flour.png",
    title: "谷物",
    titleEn: "Flour",
    price: 17.99,
  },
];

const cartData = [];

let productList = document.querySelector("#product-list");
let cartList = document.querySelector("#cart-list");

// 生成商品列表
productData.forEach((product) => {
  // getCookie(product.title)
  let li = document.createElement("li");
  li.innerHTML = `
          <img src="${product.imgUrl}" alt="">
          <h4>${product.title}</h4>
          <h5>${product.titleEn}</h5>
          <h6>¥${product.price}</h6>
          <button prod-id='${product.id}'>加入购物车</button>
      `;
  li.prod = product; // 将商品对象关联给li对象
  productList.appendChild(li);
});

// 利用事件委托将加入购物车按钮的点击事件绑定给product-list
productList.addEventListener(
  "click",
  (e) => {
    let target = e.target;
    if (target.tagName === "BUTTON") {
      let product = target.parentNode.prod;
      product.quantity = 1; // 购买数量



      //   判断当前product对象，是否在cartData中
      if (cartData.includes(product)) {

        product.quantity++;
        let numberInput = product.dom.querySelector('.number');
        numberInput.value = product.quantity;
        // document.getElementById(product.id).value = product.quantity;


      } else {
        let li = document.createElement('li');
        li.innerHTML = `
          <div class="item">
              <img src="${product.imgUrl}" alt="">
              <p>${product.title}</p>
          </div>
          <div class="price">
              <p>¥${product.price}</p>
          </div>
          <div class="quantity">
              <input type="number" class="number" id="${product.id}" value="${product.quantity}">
          </div>
          <div class="delete">
              <button>X</button>
          </div>
        `;
        cartList.appendChild(li);
        product.dom = li;
        cartData.push(product);

      }

      // 存入cookie
      setCookie(product.title, product.quantity, { secure: true })
      // 读取cookieo(╥﹏╥)o
    }
  },
  false
);
